package utils

import (
	"bytes"
	"encoding/binary"
	"strconv"
	"strings"

	gerrors "github.com/panjf2000/gnet/pkg/errors"
)

type Number interface {
	~uint8 | ~uint16 | ~uint32 | ~uint64 | ~int
}

func NumberToBytesWithBigEndian[T Number](t T) []byte {
	bytesBuffer := bytes.NewBuffer([]byte{})
	binary.Write(bytesBuffer, binary.BigEndian, t)
	return bytesBuffer.Bytes()
}

func BytesToNumber[T Number](data []byte) (t T, err error) {
	if len(data) == 0 {
		return 0, gerrors.ErrIncompletePacket
	}

	buf := bytes.NewBuffer(data)
	binary.Read(buf, binary.BigEndian, &t)
	return
}

func BytesToString(data []byte) string {
	if len(data) == 0 {
		return ""
	}

	tmp := make([]string, len(data))
	for _, v := range data {
		tmp = append(tmp, strconv.Itoa(int(v)))
	}
	return strings.Join(tmp, "")
}

// 加载数据包字段值
func LoadPacket[T ~[]byte](data []byte, fields ...T) {
	startIndex := 0
	endIndex := 0
	for _, f := range fields {
		startIndex = endIndex
		endIndex = len(f) + startIndex
		copy(f, data[startIndex:endIndex])
	}
}
